package com.leo.base.db.aop;

import com.leo.base.db.DynamicDataSourceContextHolder;
import com.leo.base.db.annotation.RandomDataSource;
import com.leo.base.db.router.rule.RandomRule;
import com.leo.base.exception.CustomException;
import com.leo.base.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author wangss
 */
@Slf4j
@Aspect
@Component
public class RandomDataSourceAspect {

    private static final String ERROR = "RandomDataSource annotation error!!!";

    @Pointcut("@annotation(com.leo.base.db.annotation.RandomDataSource)")
    public void pointcut() {
        // 不做处理
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws CustomException {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String methodName = method.getName();
        log.info("Method [{}] RandomDataSource begin to change datasource", methodName);
        RandomDataSource annotation = method.getAnnotation(RandomDataSource.class);
        if (null == annotation) {
            annotation = method.getDeclaringClass().getAnnotation(RandomDataSource.class);
            if (null == annotation) {
                log.error("Method [{}] can not find RandomDataSource annotation", methodName);
                throw new CustomException(ERROR);
            }
        }

        String tableName = annotation.tableName();
        if (StringUtils.isBlank(tableName)) {
            log.error("Method [{}] get tableName of Annotation RandomDataSource is null", methodName);
            throw new CustomException(ERROR);
        }

        RandomRule rule = (RandomRule) SpringContextUtil.getBean(tableName);
        if (null == rule) {
            log.error("Method [{}] get bean of RandomRule is null", methodName);
            throw new CustomException(ERROR);
        }

        log.info("Method [{}] RandomDataSource switching datasource to [{}]", methodName, rule.getDataSourceKey());
        DynamicDataSourceContextHolder.setDataSourceKey(rule.getDataSourceKey());
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("Method [{}] RandomDataSource execute error, reason [{}]", methodName, throwable.getMessage());
            throw new CustomException(throwable.getMessage());
        }
    }

    @After("pointcut()")
    public void after() {
        DynamicDataSourceContextHolder.clearDataSourceKey();
    }
}
